package com.kinon.tyjaccount.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.kinon.tyjaccount.R;
import com.kinon.tyjaccount.entity.GouwucheEntity;
import com.kinon.tyjaccount.tools.HttpTools;
import com.kinon.tyjaccount.tools.MyShowDialog;
import com.kinon.tyjaccount.tools.NetWorkUtil;
import com.kinon.tyjaccount.tools.ToastUtil;
import com.kinon.tyjaccount.view.JiesuanActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**晚餐*/

public class WancanFragment extends Fragment{
	private Button btn_hong;
	private Button btn_huang;
	private Button btn_qing;
	private Button btn_lan;
	private Button btn_zi;
	private Button btn_shenzi;
	private Button btn_cheng;
	private Button btn_jiesuan;
	private ListView lv_caiming;
	private Button btn_qingkong;
	private TextView tv_heji;
	private TextView tv_amount;
	double total=0.0;
	int amount=0;
	private static GouwucheAdapter gouwucheAdapter;
	/**获得数据*/
	static ArrayList<GouwucheEntity> infolist;
	HttpTools httptools=null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_wancan, null);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		initRes();
	}
	private void initRes() {
		btn_hong=(Button)getView().findViewById(R.id.btn_hong);
		btn_huang=(Button)getView().findViewById(R.id.btn_huang);
		btn_qing=(Button)getView().findViewById(R.id.btn_qing);
		btn_lan=(Button)getView().findViewById(R.id.btn_lan);
		btn_zi=(Button)getView().findViewById(R.id.btn_zi);
		btn_shenzi=(Button)getView().findViewById(R.id.btn_shenzi);
		btn_cheng=(Button)getView().findViewById(R.id.btn_cheng);
		btn_jiesuan=(Button)getView().findViewById(R.id.btn_jiesuan);
		btn_qingkong=(Button)getView().findViewById(R.id.btn_qingkong);
		lv_caiming=(ListView)getView().findViewById(R.id.lv_caiming);
		tv_heji=(TextView)getView().findViewById(R.id.tv_heji);
		tv_amount=(TextView)getView().findViewById(R.id.tv_amount);
		infolist=new ArrayList<GouwucheEntity>();
//		gouwucheAdapter = new GouwucheAdapter(getActivity(), infolist);
		gouwucheAdapter = new GouwucheAdapter(getActivity(), infolist);
		lv_caiming.setAdapter(gouwucheAdapter);
		lv_caiming.setDivider(null);
		btn_hong.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("5", "一元餐", "1", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=1;
				tv_heji.setText(""+total);
				btn_hong.setEnabled(false);
			}
		});
		btn_huang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("6", "二元餐", "2", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=2;
				tv_heji.setText(""+total);
				btn_huang.setEnabled(false);
			}
		});
		btn_qing.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("7", "三元餐", "3", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=3;
				tv_heji.setText(""+total);
				btn_qing.setEnabled(false);
			}
		});
		btn_lan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("8", "四元餐", "4", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=4;
				tv_heji.setText(""+total);
				btn_lan.setEnabled(false);
			}
		});
		btn_zi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("9", "五元餐", "5", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=5;
				tv_heji.setText(""+total);
				btn_zi.setEnabled(false);
			}
		});
		btn_shenzi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("10", "六元餐", "6", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=6;
				tv_heji.setText(""+total);
				btn_shenzi.setEnabled(false);
			}
		});
		btn_cheng.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.add(new GouwucheEntity("11", "七元餐", "7", "1"));
				gouwucheAdapter.notifyDataSetChanged();
				amount+=1;
				tv_amount.setText(""+amount);
				total+=7;
				tv_heji.setText(""+total);
				btn_cheng.setEnabled(false);
			}
		});
		btn_qingkong.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				infolist.removeAll(infolist);
				gouwucheAdapter.notifyDataSetChanged();
				total=0.0;
				amount=0;
				tv_amount.setText(""+amount);
				tv_heji.setText(""+total);
				btn_hong.setEnabled(true);
				btn_huang.setEnabled(true);
				btn_qing.setEnabled(true);
				btn_lan.setEnabled(true);
				btn_zi.setEnabled(true);
				btn_shenzi.setEnabled(true);
				btn_cheng.setEnabled(true);
			}
		});
		btn_jiesuan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				Intent intent = new Intent();
//				intent.setClass(getActivity(), JiesuanActivity.class);
//				startActivity(intent);
//				String str=JSONObject.fromObject(infolist).toString();
//				 Gson gson = new Gson(); // 实例化Gson对象
//				 String data = gson.toJson(infolist);
//				Log.e("zq", "JsonObject-------"+data);
				if (amount==0) {
					Toast.makeText(getActivity(), "请选择菜品", Toast.LENGTH_SHORT).show();
				}else {
					Saveorder();
					btn_jiesuan.setEnabled(false);
				}

			}
		});
	}

	private void Saveorder() {
//		infolist=new ArrayList<CaidanEntity>();
		if(NetWorkUtil.isNetwork(getActivity())==false)
		{
			ToastUtil toastUtil=new ToastUtil();
			toastUtil.Short(getActivity(),"  "+"当前网络不可用")
					.setToastBackground(Color.WHITE,0).show();
			return;
		}
		SharedPreferences sp = getActivity().getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		String token = sp.getString("data", "");
		Log.i("info","data---" +token);
		 Gson gson = new Gson(); // 实例化Gson对象
		 String data = gson.toJson(infolist);
		Log.e("zq", "JsonObject-------"+data);
		if (httptools == null) {
			httptools = new HttpTools(getActivity());
		}
		httptools.saveOrder(token, ""+total, data,new JsonSaveorder());

	}

	public class JsonSaveorder extends JsonHttpResponseHandler {
		@Override
		public void onStart() {
			MyShowDialog.showLoadingDialog(getActivity(), "订单生成中....");
			super.onStart();
		}

		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			MyShowDialog.closeLoadingDialog();
			try {
				Log.i("zq","提交订单--------"+response.toString());
				boolean code = response.getBoolean("code");
				String msg = response.getString("msg");
				if (code == true) {
//					Log.i("zq", "订单详情---"+response.toString());
					JSONObject object = response.getJSONObject("data");
					String orderno = object.getString("orderno");
//					String orderno
					Intent intent = new Intent();
					intent.setClass(getActivity(), JiesuanActivity.class);
					intent.putExtra("orderid", orderno);
					startActivity(intent);
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
					infolist.removeAll(infolist);
					gouwucheAdapter.notifyDataSetChanged();
					total=0.0;
					amount=0;
					tv_amount.setText(""+amount);
					tv_heji.setText(""+total);
					btn_hong.setEnabled(true);
					btn_huang.setEnabled(true);
					btn_qing.setEnabled(true);
					btn_lan.setEnabled(true);
					btn_zi.setEnabled(true);
					btn_shenzi.setEnabled(true);
					btn_cheng.setEnabled(true);
					btn_jiesuan.setEnabled(true);
				}else {
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}




	/**适配器*/
	public class GouwucheAdapter extends BaseAdapter{
		Context context;
		ArrayList<GouwucheEntity> gouwucheList;
		HttpTools httpTools=null;

		public GouwucheAdapter(Context context, ArrayList<GouwucheEntity> gouwucheList) {
			super();
			this.context = context;
			this.gouwucheList = gouwucheList;
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return gouwucheList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return gouwucheList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View view, ViewGroup parent) {
			final ViewHandle handle;
			if(view==null){
				handle=new ViewHandle();
				view=LayoutInflater.from(context).inflate(R.layout.item_gouwuche, null);
				handle.tv_shangpinming=(TextView)view.findViewById(R.id.tv_shangpinming2);
				handle.tv_price=(TextView)view.findViewById(R.id.tv_price2);
				handle.ib_add=(ImageButton)view.findViewById(R.id.ib_add2);
				handle.ib_less=(ImageButton)view.findViewById(R.id.ib_less2);
				handle.et_amout=(EditText)view.findViewById(R.id.et_amount2);
				view.setTag(handle);
			}else {
				handle = (ViewHandle) view.getTag();
			}
			handle.tv_shangpinming.setText(gouwucheList.get(position).getName());
			handle.tv_price.setText("￥"+gouwucheList.get(position).getPrice());

			//数量
			handle.et_amout.setText(gouwucheList.get(position).getAmount());

			//加
			handle.ib_add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
//					addGoods(position, handle.et_amout,handle.tv_lim);
					int goodsNum = Integer.parseInt(handle.et_amout.getText().toString());
					goodsNum++;
					handle.et_amout.setText(""+goodsNum);
					total+=Double.parseDouble(gouwucheList.get(position).getPrice());
					amount++;
					gouwucheList.get(position).setAmount(goodsNum+"");
					tv_heji.setText(""+total);
					tv_amount.setText(""+amount);
				}
			});
			//减
			handle.ib_less.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					int goodsNum = Integer.parseInt(handle.et_amout.getText().toString());
//					lessGoods(position,handle.et_amout,goodsNum,handle.tv_lim);
					goodsNum--;
					handle.et_amout.setText(""+goodsNum);
					total-=Double.parseDouble(gouwucheList.get(position).getPrice());
					amount--;
					gouwucheList.get(position).setAmount(goodsNum+"");
					tv_heji.setText(""+total);
					tv_amount.setText(""+amount);
					if (goodsNum<=0) {
					if (gouwucheList.get(position).getId().equals("5")) {
						btn_hong.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("6")){
						btn_huang.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("7")){
						btn_qing.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("8")){
						btn_lan.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("9")){
						btn_zi.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("10")){
						btn_shenzi.setEnabled(true);
					}else if(gouwucheList.get(position).getId().equals("11")){
						btn_cheng.setEnabled(true);
					}
					gouwucheList.remove(position);
					notifyDataSetChanged();

					}
				}
			});
//			//删除
//			handle.ib_delete.setOnClickListener(new OnClickListener() {
	//
//				@Override
//				public void onClick(View v) {
//					deletegoods(position);
	//
//				}
//			});
			return view;
		}

		/** 增加商品 */
//		private void addGoods(final int index, final EditText editText,final TextView tv) {
//			if(NetWorkUtil.isNetwork(context)==false)
//			{
//				Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
//				return;
//			}if("".equals(editText.getText().toString())){
//				editText.setText(0+"");
//			}
//			SharedPreferences sp = context.getSharedPreferences("spReg",
//					Context.MODE_PRIVATE);
//			String token = sp.getString("data", "");
//			if (httpTools == null) {
//				httpTools = new HttpTools(context);
//			}
//			int goodsNum = Integer.parseInt(editText.getText().toString());
//			goodsNum++;
//			if (goodsNum>Integer.parseInt(gouwucheList.get(index).getPerlim()) && !gouwucheList.get(index).getPerlim().equals("0")) {
//				Toast.makeText(context, "每人限购"+gouwucheList.get(index).getPerlim()+"份", Toast.LENGTH_SHORT).show();
//				return;
//			}
//			httpTools.addgoodscat(token, gouwucheList.get(index).getProductid(), goodsNum+"",
//					new JsonHttpResponseHandler() {
	//
//				@Override
//				public void onSuccess(int statusCode, Header[] headers,
//						JSONObject response) {
//					// TODO Auto-generated method stub
//					super.onSuccess(statusCode, headers, response);
//					try {
//						Log.i("zq", response.toString());
//						boolean code = response.getBoolean("code");
//						String msg = response.getString("msg");
//						if (code == true) {
//							JSONObject data = response.getJSONObject("data");
//							String amount = data.getString("amount");
//							String total = data.getString("total");
//							int goodsNum = Integer.parseInt(editText.getText().toString());
//							goodsNum++;
//							editText.setText(goodsNum + "");
//							int lim = Integer.parseInt(gouwucheList.get(index).getPerlim());
//							int stock = Integer.parseInt(gouwucheList.get(index).getStock());
//							setMsg("jia", ""+goodsNum, index);
//							setMsg("zongjia",total,0);
////							setMsg("qingchu",""+goodsNum,index);
//						} else {
//							Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
//						}
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
	//
//			});
//		}

		/**减少商品*/
//		private void lessGoods(final int index, final EditText editText, int goodsNum,final TextView tv) {
//			if(NetWorkUtil.isNetwork(context)==false)
//			{
//				Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
//				return;
//			}
//			if("".equals(editText.getText().toString())){
//				editText.setText(0+"");
//				goodsNum=0;
//			}
//			SharedPreferences sp = context.getSharedPreferences("spReg",
//					Context.MODE_PRIVATE);
//			String token = sp.getString("data", "");
	//
//			if (httpTools == null) {
//				httpTools = new HttpTools(context);
//			}
	//
//			if(goodsNum<=1)
//			{
//				deletegoods(index);
//				return;
////				setMsg("jia", "0", index);
////				gouwucheList.remove(index);
////				notifyDataSetChanged();
//			}
//			goodsNum--;
//			httpTools.addgoodscat(token, gouwucheList.get(index).getProductid(), goodsNum+"",
//					new JsonHttpResponseHandler() {
	//
//				@Override
//				public void onSuccess(int statusCode, Header[] headers,
//						JSONObject response) {
//					// TODO Auto-generated method stub
//					super.onSuccess(statusCode, headers, response);
//					try {
//						Log.i("info", response.toString());
//						boolean code = response.getBoolean("code");
//						String msg = response.getString("msg");
//						int goodsNum = Integer.parseInt(editText.getText().toString());
//						if (code == true) {
//							JSONObject data = response.getJSONObject("data");
//							String amount = data.getString("amount");
//							String total = data.getString("total");
//							int goodsNum2 = Integer.parseInt(editText.getText().toString());
//							goodsNum--;
//							editText.setText(goodsNum + "");
////							int lim = Integer.parseInt(gouwucheList.get(index).getLim());
////							if(goodsNum<=lim){
////								tv.setVisibility(View.GONE);
//////								tv.setText("仅剩"+gouwucheList.get(index).getLim()+"份");
////							}
//							setMsg("jian", goodsNum+"", index);
//							setMsg("zongjia",total,0);
////							setMsg("qingchu",""+goodsNum,index);
//						} else {
//							Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
//						}
//					} catch (JSONException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//				}
	//
//			});
//		}

		}
		class ViewHandle {
			/**商品名*/
			TextView tv_shangpinming;
			/**价格*/
			TextView tv_price;
			/**加*/
			ImageButton ib_add;
			/**减*/
			ImageButton ib_less;
			/**删除*/
			ImageButton ib_delete;
			/**数量*/
			EditText et_amout;
		}

}
